import React, { useEffect, useContext, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom"
import dianzan from "../../assets/images/dianzan.png"
import pinglun from "../../assets/images/pinglun.png"
import { AuthContext } from '../../contexts/authContext';
// import { getArticles } from "../../fake-api"
import { createindexDB, getAllData } from "../../utils/IndexDB";
import "./message.css"
import { Loading } from "../Loading/Loading";
import _ from "lodash";
import axios from "axios";

export const Message = () => {

    let { pathname, search } = useLocation()
    let navigate = useNavigate();
   
    const { state, dispatch } = useContext(AuthContext)
    const [loading, setLoading] = useState(true)
    // 因为接口的原因，默认每次只返回10条数据，但在请求结果中会有该分类下的所有数据，使用offset排除已经得到过的数据。
    //  id 存储当前 category_id, 确保点击  三个tab的时候不会 丢失
    let offset = 0, id = state.category_id, historyOffset = 0
    // 获取路径中的参数， 用来传入文章接口获取相应的tab文章
    let sortBy = search.split("=")[1]
    // 跳转到文章详情页，并且将该文章加入indexDB 数据库，防止刷新和关闭会导致历史记录丢失。
    const gotoDetail = async (props) => {
        // await createindexDB(props)
        console.log(props,"-----");
        let oldIds = JSON.parse(localStorage.getItem('ids'))
        console.log(oldIds,"==");
        if (!oldIds.includes(props.article_id)){
            localStorage.setItem('ids', JSON.stringify([props.article_id, ...oldIds]))
        }else {
            // 存在记录则调换位置
            localStorage.setItem('ids', JSON.stringify(Array.from(new Set([props.article_id, ...oldIds]))))
        }
        navigate(`/post/${props.article_id}`, {
            state: {
                articles: props
            }
        })
    }
    const callback = (data) => {
        dispatch({ articles: data })   
    }
    // scroll 事件的回调， 作用： 获取下一批 10条数据， 然后将其dispatch  更新数据
    const handleScroll = async (e) => {
        const { clientHeight, scrollTop, scrollHeight } = e.target.scrollingElement

        if (clientHeight + scrollTop === scrollHeight && state.articles) {
            if (sortBy == "history") {
                historyOffset++

                let ids = JSON.parse(localStorage.getItem('ids')), HistoryArticles = []
                for (let i = historyOffset * 10;i< ids.length; i++){
                    result = await axios.post('/api/getArticleById', { articleId: parseInt(ids[i])})
                    // HistoryArticles = [...HistoryArticles, ...result.data.data.articles]

                }

                dispatch({ moreArticles: HistoryArticles })
            } else {
                offset++

                let result = await axios.post('/api/getArticles', { categoryId: id, sortBy: sortBy, offset: offset * 10 })

                dispatch({ moreArticles: result.data.data.articles })
            }
        }
     

    }
    useEffect(async () => {

        let result = {
            data: {
                articles: []
            }
        }
        // 在数据流中 初始状态中没有category_id 属性，但组件渲染是从最里的子组件开始
        if (state.category_id >= 0) {
            
            // 根据路径参数中的值来区分 热门 、最新 、 历史三个tab，获取不同的文章列表数据
            if (sortBy == "history") {
                let ids = JSON.parse(localStorage.getItem('ids')), HistoryArticles = []
                for(let i = 0;i< ids.length; i++){
                    let res = await axios.post('/api/getArticleById', { articleId: ids[i] })
                    HistoryArticles = [...HistoryArticles, res.data.data.article]
                    console.log(res, HistoryArticles, "history---");

                }
                await dispatch({ articles: HistoryArticles })
            } else {
                result = await axios.post('/api/getArticles', { categoryId: state.category_id, sortBy: sortBy })

                // let res = await axios.post('/api/getArticleById', { articleId: "6987577629272440846"})
                // console.log(result.data.data.articles[0], res.data.data.article,'res');
                await dispatch({ articles: result.data.data.articles })
            }
        }
        
        //加入state.category_id ,因为这里需要用到state.category_id，只有根据state.category_id的变化来更新页面
    }, [search, pathname, state.category_id])
    useEffect(() => {
        // 给window 绑定scroll 事件， 使用lodash 进行节流， 1秒只能触发一次
        window.addEventListener('scroll', _.throttle(handleScroll, 1000, { trailing: true }))
        // 组件销毁， 解除绑定的scroll事件
        return () => {
            window.removeEventListener('scroll', () => { console.log("scroll移除了"); })
        }
    }, [])

    return (
        <>
            {
                loading && state.articles ? state.articles.map(item => {
                    return (
                        <div className="article-wrapper" key={item.article_id} onClick={() => gotoDetail(item)}>
                            <div className="article-info">
                                <span>{item.author_user_info.user_name}</span>
                                <span className="article-info-separate">|</span>
                                <span>
                                    {/* {new Date(item.article_info.mtime - item.article_info.ctime)} */}
                                    {
                                        Math.ceil((item.article_info.mtime - item.article_info.ctime) / (1000 * 60)) + "分钟前"
                                    }
                                </span>
                            </div>
                            <div className="article-tag">
                                {item.category_info?.first_category_name}
                            </div>
                            <div className="article-tag second_category">
                                {item.category_info?.second_category_name}
                            </div>
                            <div className="article-title">
                                <h2><b>{item.article_info.title}</b></h2>
                            </div>
                            <div className="article-midWrapper">
                                <div>
                                    <div className="articles-body">
                                        {item.article_info.brief_content}
                                    </div>
                                    <ul className="article-comment">
                                        <li>
                                            <img className="article-icon" src={dianzan} alt="" />
                                            <span className="article-count">{item.article_info.digg_count}</span>
                                        </li>
                                        <li>
                                            <img className="article-icon" src={pinglun} alt="" />
                                            <span className="article-count">{item.article_info.comment_count}</span>
                                        </li>
                                    </ul>
                                </div>

                                <img className="article-img" src={item.article_info.cover_image} alt="" />
                            </div>
                        </div>
                    )
                }) : <Loading />
            }
        </>

    )
}